package springmvc.web.ingredients;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Data;

import org.dhbw.cocktail.Ingredient;
import org.dhbw.cocktail.mixer.ICocktailMixer;
import org.dhbw.cocktail.mixer.MixerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Manage and select ingredients	
 * 
 * @author Roland von Werden
 */
@Data
public class IngredientController implements Controller {

	/**
	 * autowirde mixerfactory to access methods to create, get and search
	 * persisted Objects
	 */
	@Autowired
	@Qualifier("cocktail_mixer_factory")
	MixerFactory mixerFactory;

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse arg1) throws Exception {
		ModelAndView mav = new ModelAndView();

		// Retrieve Specified ingredient and all cocktails that are using it
		if (request.getParameter("id") != null) {
			// Alter amount of an ingredient if requested
			if (request.getParameter("amount") != null) {
				try {
					double amount = Double.valueOf((String)request.getParameter("amount"));
					alterAmountOfIngredient(Long.valueOf((String)request.getParameter("id")), amount);
				} catch (NumberFormatException e) {
				}
			}
			mav.addObject("ingredient", mixerFactory.getCocktailMixer().getIngredientById(Long.valueOf((String)request.getParameter("id"))));
			mav.addObject("cocktails", mixerFactory.getCocktailMixer().getCocktailsByIngredientId(Long.valueOf((String)request.getParameter("id"))));
		}
		else {
			// Retrieve all ingredients to display a selection for the user
			mav.addObject("ingredients", mixerFactory.getCocktailMixer().getIngredients());
		}

		return mav;
	}

	@Transactional
	private void alterAmountOfIngredient(long id, double newAmount) {
		 ICocktailMixer mxier = mixerFactory.getCocktailMixer();
		 Ingredient ingr = mxier.getIngredientById(id);
		 ingr.setAmount(newAmount);
		 mxier.saveIngredient(ingr);
	}

}
